package com.sk.cartoonindia;

import java.net.URLEncoder;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sk.cartoonindia.R;
import com.sk.utility.AsyncTaskCompleteListener;
import com.sk.utility.Constants.FeedID;
import com.sk.utility.Constants;
import com.sk.utility.Downloader;
import com.sk.utility.ImageAdapter;
import com.sk.utility.ToonGallery;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.os.StrictMode;

/**
 * @author saurabh
 * Activity to show cartoon on screen
 */
public class ShowToonsActivity extends Activity implements
		AsyncTaskCompleteListener {

	ArrayList<String> toonPaths = new ArrayList<String>();
	ToonGallery gallery;
	ImageAdapter myAdapter;

	// ArrayList<String> imgName = new ArrayList<String>();
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		if (Constants.DEVELOPER_MODE) {

			StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
					.detectAll().penaltyLog().penaltyDialog().build());
			StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
					.detectAll().penaltyLog().penaltyDeath().build());
		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.toon);
		// this.getWindowManager().getDefaultDisplay();

		gallery = (ToonGallery) findViewById(R.id.gallery);
		// gallery.setOnItemSelectedListener(OnItemSelectedListener);
		getFeed();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add("Clear Cache!");
		// menu.add(R.string.schedule);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case 0:
			myAdapter.imgSource.clearCache();
			return false;
		default:
			return super.onOptionsItemSelected(item);
		}

	}

	@Override
	public void onDestroy() {
		gallery.setAdapter(null);
		super.onDestroy();
	}

	/*
	 * private AdapterView.OnItemSelectedListener OnItemSelectedListener = new
	 * AdapterView.OnItemSelectedListener() {
	 * 
	 * @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int
	 * arg2, long arg3) { // FetchImages(arg2);
	 * 
	 * }
	 * 
	 * @Override public void onNothingSelected(AdapterView<?> arg0) { }
	 * 
	 * };
	 */
	private ProgressDialog progressDialog;

	private void getFeed() {
		final String feedurl = getFeedURL();
		Downloader dn = new Downloader();

		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setMessage("Loading Feed...");
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setProgress(0);
		progressDialog.show();

		dn.downloadJSONFeed(feedurl, this, ShowToonsActivity.this);
	}

	private ArrayList<String> JSON2ArrayList(String feed) {
		String pathPrefix = "http://www.cartoonindia.com/toons/";
		ArrayList<String> toonPaths = new ArrayList<String>();
		try {
			int entries = 0;
			JSONArray jsonArray = new JSONArray(feed);
			entries = jsonArray.length();
			Log.i("GET", "Downloaded - " + entries + " feed entries");
			for (int i = 0; i < entries; i++) {
				JSONObject jsonObject = jsonArray.getJSONObject(i);
				StringBuilder sb = new StringBuilder();
				sb.append(pathPrefix);
				sb.append(jsonObject.getString("fpath"));
				sb.append(jsonObject.getString("fname"));
				toonPaths.add(sb.toString());
			}

		} catch (JSONException e) {
			Log.e("JSONException", e.getMessage());
		}
		return toonPaths;
	}

	private String getFeedURL() {
		Bundle extras = getIntent().getExtras();
		String catName = "";
		if (extras != null) {
			catName = extras.getString("catName");
		}

		String feedurl;
		if (catName == "") {
			feedurl = Constants.urlRandomCartoon;
		} else {
			Log.i("ShowToonsActivity", "Selected category " + catName);
			feedurl = String.format(Constants.urlCategoryBasedCartoon,
					URLEncoder.encode(catName));

		}

		return feedurl;
	}

	@Override
	public void onTaskComplete(String result, FeedID feedId) {
		switch (feedId) {
		case FEED:
			String ret = result;
			progressDialog.dismiss();
			toonPaths = JSON2ArrayList(ret);

			if (toonPaths.size() > 0) {
				/*
				 * progressDialog = new ProgressDialog(this);
				 * progressDialog.setCancelable(true);
				 * progressDialog.setMessage("Getting cartoons...");
				 * progressDialog
				 * .setProgressStyle(ProgressDialog.STYLE_SPINNER);
				 * progressDialog.setProgress(0); progressDialog.show();
				 */
				myAdapter = new ImageAdapter(ShowToonsActivity.this, toonPaths);
				// myAdapter.imgSource.clearCache();
				// myAdapter.notifyDataSetChanged();
				gallery.setAdapter(myAdapter);
				/* FetchImages(currentPosition); */
			} else {
				Toast.makeText(ShowToonsActivity.this,
						"Unable to download cartoon feed", Toast.LENGTH_LONG)
						.show();
			}
			break;
		}
	}

	/*
	 * private void FetchImages(int position) { int preLoadCount = 2; int
	 * loadTill = 0; int loadFrom = 0;
	 * 
	 * if (position == 0) { loadFrom = position; loadTill = preLoadCount; } else
	 * { loadFrom = position + preLoadCount; loadTill = loadFrom; }
	 * 
	 * Downloader bmpSource = new Downloader(); String path = ""; if
	 * (Environment.getExternalStorageState().equals(
	 * Environment.MEDIA_MOUNTED)) { path =
	 * this.getExternalCacheDir().getAbsolutePath() + "/"; }
	 * 
	 * for (int i = loadFrom; i <= loadTill; i++) { final String toonPath =
	 * toonPaths.get(i); final String fname = toonPath.substring(
	 * toonPath.lastIndexOf("/") + 1, toonPath.lastIndexOf(".")); // if
	 * (imgName.indexOf(fname) == -1) { bmpSource.getBMP(toonPath, path, this,
	 * ShowToonsActivity.this); // }
	 * 
	 * }
	 * 
	 * }
	 */
}
